package org.zhangkun.jmsg.bean;

import java.io.UnsupportedEncodingException;

import org.zhangkun.jmsg.core.UserManager;

/**
 * 对数据进行封包
 * 
 * @author zhangkun
 * 
 */
public class DataPack extends DataPackage {

	public DataPack() {
		setSenderHostName(UserManager.me.getHostName());
		setSenderUsername(UserManager.me.getUsername());
		setSenderName(UserManager.me.getName());
		setMsg(new String(change(UserManager.me.getName(),
				UserManager.me.getGroup())));
		setVersion("1_jmsg");
	}

	public byte[] change(String str1, String str2) {
		byte[] b1 = str1.getBytes();
		byte[] b2 = str2.getBytes();
		byte[] b3 = new byte[b1.length + b2.length + 1];
		System.arraycopy(b1, 0, b3, 0, b1.length);
		b3[b1.length] = 0;
		if (b2.length >= 1) {
			System.arraycopy(b2, 0, b3, b1.length + 1, b2.length);
		}
		return b3;
	}

	public byte[] getData() {
		// TODO Auto-generated method stub
		return this.toString().getBytes();
	}

	public byte[] getData(String coding) {
		// TODO Auto-generated method stub
		try {
			return this.toString().getBytes(coding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			System.out.println("未知的编码" + coding + "。");
			return getData();
		}
	}

	public String toString() {
		return (getVersion() + ":" + getDataID() + ":" + getSenderUsername()
				+ ":" + getSenderHostName() + ":" + getDataType() + ":" + getMsg());
	}

}
